package com.epam.qanda.web.servlet.authentication;

import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.UserService;
import com.epam.qanda.hash.MD5;
import com.epam.qanda.mail.EmailUtility;

public class ForgotPasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");

	public ForgotPasswordServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String email = request.getParameter("inputEmail");
		UserService service = new UserService();

		User user = service.getUserByEmail(email);

		if (user != null) {
			if (user.isConfirmationStatus() != false) {
				SecureRandom random = new SecureRandom();
				String newPassword = new BigInteger(50, random).toString(15);

				user.setPassword(MD5.getHash(newPassword));

				StringBuilder message = new StringBuilder();
				message.append("http://");
				message.append(request.getServerName() + ":");
				message.append(request.getServerPort());
				message.append(request.getContextPath());
				
				
				try {
					new EmailUtility().sendEmail("New password", "You new password " + newPassword
							+ " " + message, user);
				} catch (MessagingException e) {
					LOG.warn(e.getMessage());
				}
				service.update(user);
				response.sendRedirect("pmain");
			} else {
				request.setAttribute("errorMessage", 1);//not confirmed
				request.getRequestDispatcher(request.getHeader("Referer")).forward(request,
						response);
			}
		} else {
			request.setAttribute("errorMessage", 2);//wrong mail
			//request.getRequestDispatcher(request.getHeader("Referer")).forward(request, response);
			request.getRequestDispatcher("forgotPasswordPage").forward(request, response);
		}

	}

}
